<template>
  <view class="container">
    <ul class="categories">
      <li v-for="item in categories" :key="item" @click="handleClick(item)">
        {{ item }}
      </li>
    </ul>
    <div class="goods-section">
      <div v-if="goodsList.length > 0">
        <ul class="goods-list">
          <li v-for="goods in goodsList" :key="goods.goodsId" @click="goToGoodsDetails(goods.goodsId)">
            <image :src="goods.images" ></image>
            <p>{{ goods.goodsName }}</p>
          </li>
        </ul>
      </div>
      <div v-else-if="selectedCategory">
        <p>没有找到 {{ selectedCategory }} 分类下的商品。</p>
      </div>
    </div>
  </view>
</template>

<script>
import config from '@/config';

export default {
  data() {
    return {
      categories: ['食物', '护理', '玩具', '用品', '训练用品', '健康', '床垫和窝'],
      selectedCategory: '',
      goodsList: []
    };
  },
  methods: {
    handleClick(category) {
      this.selectedCategory = category;
      this.fetchGoodsByCategory(category);
    },
    fetchGoodsByCategory(category) {
      uni.request({
        url: `${config.apiUrl}/goods/getCategory`,
        method: 'GET',
        data: { category: category },
        success: (response) => {
          if (response.statusCode === 200) {
            this.goodsList = response.data || []; // Ensure we have a default empty array
            console.log('Fetched goods data:', response.data);
          } else {
            this.goodsList = [];
            console.error('Error fetching goods data:', response);
          }
        },
        fail: (error) => {
          this.goodsList = [];
          console.error('Error fetching goods data:', error);
        }
      });
    },
    goToGoodsDetails(goodsId) {
      uni.navigateTo({
        url: `/pages/goodsDetail/goodsDetail?goodsId=${goodsId}`
      });
    }
  }
};
</script>

<style>
.container {
  display: flex;
  flex-direction: row;
}

ul.categories {
  list-style-type: none;
  padding: 0;
  margin: 0;
  width: 100px;
}

ul.categories li {
  padding: 10px;
  cursor: pointer;
}

ul.categories li:hover {
  background-color: #f0f0f0;
}

.goods-section {
  flex: 1;
  padding: 10px;
}

.goods-list {
  list-style-type: none;
  padding: 0;
  margin: 0;
  display: flex;
  flex-wrap: wrap;
}

.goods-list li {
  width: calc(50% - 20px); /* Two items per row */
  margin: 10px;
  box-sizing: border-box;
}

image {
  width: 150rpx;
  height: 150rpx;
  margin-right: 15rpx;
  border-radius: 15px;
}
</style>
